from django_filters import rest_framework as filters
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, mixins

from alarm.models import Alarm
from alarm.serializers import AlarmSerializer, AlarmRetrieveSerializer, AlarmCategorySerializer
from company.models import VehicleCompanyTerminal


class AlarmFilter(filters.FilterSet):
    license_number = filters.CharFilter(field_name='vehicle__license_number')
    alarm_type = filters.CharFilter(method='filterset_alarm_type')
    category = filters.CharFilter(field_name='category')
    start_time = filters.DateTimeFilter(field_name='start_time', lookup_expr='gte')
    end_time = filters.DateTimeFilter(field_name='end_time', lookup_expr='lt')
    media_uri_category = filters.CharFilter(field_name='media_uri_category')

    def filterset_alarm_type(self, queryset, name, value):
        if value == "":
            return queryset
        elif int(value) == 0:
            # 司机报警
            return queryset.filter(category__in=[35, 36, 37, 38, 39, 40])
        else:
            # 车辆报警
            return queryset.filter(category__in=[1, 41, 42, 43, 44, 45, 46, 47])

    class Meta:
        model = Alarm
        fields = ('license_number', 'category', 'start_time', 'end_time', 'media_uri_category', 'alarm_type')


class AlarmViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    queryset = Alarm.objects.all()
    filterset_class = AlarmFilter

    def get_serializer_class(self):
        if self.action == "retrieve":
            return AlarmRetrieveSerializer
        return AlarmSerializer

    def get_queryset(self):
        company = self.request.user.company
        vehicle_ids = VehicleCompanyTerminal.objects.filter(company=company).values_list('vehicle_id', flat=True)
        return Alarm.objects.filter(vehicle_id__in=vehicle_ids)


class AlarmCategoryView(mixins.ListModelMixin, GenericViewSet):
    queryset = Alarm.objects.all()
    serializer_class = AlarmCategorySerializer
    pagination_class = None

    def list(self, request, *args, **kwargs):
        instance = self.queryset.get(id=1)
        return Response(dict(instance.CategoryChoice))
